package com.marion.langchain4jdemo.service;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import com.marion.langchain4jdemo.model.DeviceDTO;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 设备服务类
 */
@Slf4j
@Service
public class DeviceService {
    private static final String URL = "http://teamx-lcapp-webaddedinternal.dockeruat.lefile.cn/openapi/membership/device/list/all";
    private static final String GATEWAY_LID = "10233345539";
    private final RestTemplate restTemplate;

    public DeviceService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @Tool(description = "获取用户的联想设备（已绑定/未绑定/soit）列表信息")
    public List<DeviceDTO> fetchDeviceList(
            @ToolParam(description = "用户UID") long uid) {
        log.info("Fetching device list with uid: {}", uid);
        try {
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.set("GATEWAY-LID", uid + "");
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

            // 设置请求体
            MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
            requestBody.add("cursor", "1_0:1_0");
            requestBody.add("pageSize", "100");

            // 创建HTTP实体
            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(requestBody, headers);

            // 发送请求并接收响应
            ResponseEntity<Map> response = restTemplate.exchange(
                    URL,
                    HttpMethod.POST,
                    requestEntity,
                    Map.class
            );

            Map<String, Object> responseBody = response.getBody();

            // 检查响应状态，只有status=0时才返回res中的devices
            if (responseBody != null &&
                    responseBody.containsKey("status") &&
                    Integer.valueOf(0).equals(responseBody.get("status")) &&
                    responseBody.containsKey("res")) {

                Map<String, Object> res = (Map<String, Object>) responseBody.get("res");
                List<Map<String, Object>> deviceMaps = (List<Map<String, Object>>) res.getOrDefault("devices", List.of());

                return deviceMaps.stream()
                        .map(this::convertToDeviceDTO)
                        .collect(Collectors.toList());
            } else {
                // 返回空列表
                log.warn("Device list API returned non-zero status or missing 'res', returning empty device list");
                return Collections.emptyList();
            }
        } catch (Exception e) {
            log.error("Error occurred while fetching device list: {}", e.getMessage(), e);
            throw new RuntimeException("获取设备列表失败", e);
        }
    }

    private DeviceDTO convertToDeviceDTO(Map<String, Object> deviceMap) {
        return JSON.parseObject(JSON.toJSONString(deviceMap), DeviceDTO.class);
    }
}
